/**
 * 
 */
package idv.takeshi.software.productline.bookstore.presentation.web.filter;

import idv.takeshi.software.productline.bookstore.application.service.BrowseBooksService;
import idv.takeshi.software.productline.bookstore.domain.model.category.Category;
import idv.takeshi.software.productline.bookstore.domain.model.shoppingcart.ShoppingCart;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Initial global session attributes
 * @author takeshi
 *
 */
public class InitialSessionAttributesFilter implements Filter {
	
	@Autowired
	private BrowseBooksService browseBookService;
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws ServletException, IOException {
		
		Long sidebarCategoryId = null;
		Category rootCategory = null;
		Category sidebarCategory = null;
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession();
		ShoppingCart shoppingCart = null;
		
		if(null == session.getAttribute("rootCategory")){
			rootCategory = browseBookService.getRootCategory();
			
		}
		if(StringUtils.isNotBlank(request.getParameter("sidebarCategoryId"))){
			sidebarCategoryId = new Long(request.getParameter("sidebarCategoryId"));
			sidebarCategory = rootCategory.getAllSubCategory(sidebarCategoryId);
		} else{
			sidebarCategory = (Category) session.getAttribute("sidebarCategory");
		}
		
		if(null == session.getAttribute("shoppingCart")){
			shoppingCart = new ShoppingCart();
		} else{
			shoppingCart = (ShoppingCart) session.getAttribute("shoppingCart");
		}
		
		session.setAttribute("rootCategory", rootCategory);
		session.setAttribute("sidebarCategory", sidebarCategory);
		session.setAttribute("shoppingCart", shoppingCart);
		
		filterChain.doFilter(request, response);
	}

	public void destroy() {
		//DO NOTHING
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		//DO NOTHING
	}

}
